package com.systop.dxjj.common.filter;

import com.alibaba.fastjson.JSON;
import com.systop.dxjj.common.pojo.StudentUser;
import com.systop.dxjj.common.pojo.TeacherUser;
import com.systop.dxjj.common.pojo.User;
import com.systop.dxjj.common.pojo.Useruse;
import com.systop.dxjj.common.utils.JwtUtil;
import com.systop.dxjj.common.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;

    TeacherUser teacherUser;

    Useruse useruse;

    StudentUser studentUser;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//        if(request.getMethod().equals("OPTIONS")){
//            filterChain.doFilter(request, response);
//            return;
//        }
         //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token

        String teaid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            teaid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        String stuid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            stuid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        String userid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        //从redis中获取用户信息
        String sturedisKey = "stulogin:" + stuid;
        String tearedisKey = "login:" + teaid;
        String useredisKey = "uselogin:" + userid;
        Object cacheObject = redisCache.getCacheObject(tearedisKey);
        Object cacheObject2 = redisCache.getCacheObject(sturedisKey);
        Object cacheObject3 = redisCache.getCacheObject(useredisKey);

        if(!Objects.isNull(cacheObject)) {
            if (cacheObject instanceof TeacherUser) {
                teacherUser = (TeacherUser) cacheObject;
            } else {
                teacherUser = JSON.parseObject(JSON.toJSON(cacheObject).toString(), TeacherUser.class);
            }
            if (Objects.isNull(teacherUser)) {
                throw new RuntimeException("用户未登录");
            }
            //存入SecurityContextHolder
            //TODO 获取权限信息封装到Authentication中
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(teacherUser, null, null);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            //放行
            filterChain.doFilter(request, response);
        }else if (!Objects.isNull(cacheObject2)){
            if (cacheObject2 instanceof StudentUser) {
                studentUser = (StudentUser) cacheObject2;
            } else {
                studentUser = JSON.parseObject(JSON.toJSON(cacheObject2).toString(), StudentUser.class);
            }
            if(Objects.isNull(studentUser)){
                throw new RuntimeException("用户未登录");
            }
            //存入SecurityContextHolder
            //TODO 获取权限信息封装到Authentication中
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(studentUser,null,null);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            //放行
            filterChain.doFilter(request, response);
        }else {
            if (cacheObject3 instanceof Useruse) {
                useruse = (Useruse) cacheObject3;
            } else {
                useruse = JSON.parseObject(JSON.toJSON(cacheObject3).toString(), Useruse.class);
            }
            if(Objects.isNull(useruse)){
                throw new RuntimeException("用户未登录");
            }
            //存入SecurityContextHolder
            //TODO 获取权限信息封装到Authentication中
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(useruse,null,null);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            //放行
            filterChain.doFilter(request, response);
        }

    }
}

